import { createRouter, createWebHashHistory } from "vue-router";
import { ElNotification } from "element-plus";
import store from "@/store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import tool from "@/utils/tool";
import systemRouter from "./systemRouter";
import userRoutes from "@/config/route";
import { beforeEach, afterEach } from "./scrollBehavior";
// 系统路由
const routes = systemRouter;
// 动态引入 views 目录下的 Vue 组件
const modules = import.meta.glob("../views/**/**.vue");
// 系统404特殊路由
const routes_404 = {
  path: "/:pathMatch(.*)*",
  hidden: true,
  component: () => import("@/layout/other/404.vue"),
};
// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...routes, routes_404],
});
//判断是否已加载过动态/静态路由
var isGetRouter = false;
// 路由跳转前的处理逻辑
router.beforeEach(async (to, from, next) => {
  // 获取系统配置，如果未获取则尝试获取
  if (!store.state.system.base.app_name) {
    try {
      await store.dispatch("GET_CONFIG", 'base');
    } catch (error) {
      console.error("Error loading configuration:", error);
    }
  }
  // 开始显示进度条
  NProgress.start();
  // 动态标题
  document.title = to.meta.title ? `${to.meta.title} - ${store.state.system.base.site_name}` : `${store.state.system.base.site_name}`;
  // 获取登陆token
  let token = tool.cookie.get("token");
  // 如果访问的是登录路由，则重置动态路由加载状态并继续
  if (to.path === "/login") {
    //删除路由(替换当前layout路由)
    router.addRoute(routes[0]);
    isGetRouter = false;
    next();
    return false;
  }
  // 检查当前访问的路由是否已在静态路由列表中
  if (routes.findIndex((r) => r.path === to.path) >= 0) {
    next();
    return false;
  }
  // 如果未登录且访问的不是登录路由，则重定向到登录路由
  if (!token && to.path != "/login") {
    next({ path: "/login" });
    return false;
  }
  // 整页路由处理
  if (to.meta.fullpage) {
    to.matched = [to.matched[to.matched.length - 1]];
  }
  // 加载动态/静态路由
  if (!isGetRouter) {
    loadRoutes();
    router.push(to.fullPath);
    isGetRouter = true;
  }
  beforeEach(to, from)
  next();
});
// 路由跳转后的处理逻辑
router.afterEach((to, from) => {
  // 执行自定义的 afterEach 处理
  afterEach(to, from);
  // 完成进度条显示
  NProgress.done();
});
// 路由错误处理
router.onError((error) => {
  // 完成进度条显示
  NProgress.done();
  // 显示错误信息
  ElNotification.error({
    title: "路由错误",
    message: error.message,
  });
});
// 入侵追加自定义方法、对象
router.sc_getMenu = () => {
  var apiMenu = tool.data.get("MENU") || [];
  let userInfo = tool.data.get("USER_INFO");
  let userMenu = treeFilter(userRoutes, (node) => {
    return node.meta.role
      ? node.meta.role.filter((item) => userInfo.role.indexOf(item) > -1)
          .length > 0
      : true;
  });
  var menu = [...userMenu, ...filterTree(apiMenu)];
  return menu;
};
// 动态加载路由
function loadRoutes() {
  // 获取用户菜单
  let apiMenu = tool.data.get("MENU") || [];
  let userInfo = tool.data.get("USER_INFO");
  let userMenu = treeFilter(userRoutes, (node) => {
    return node.meta.role
      ? node.meta.role.filter((item) => userInfo.role.indexOf(item) > -1)
          .length > 0
      : true;
  });
  let menu = [...userMenu, ...filterTree(apiMenu)];
  // 过滤并转换菜单为路由
  var menuRouter = filterAsyncRouter(menu);
  // 扁平化路由
  menuRouter = flatAsyncRoutes(menuRouter);
  // 将路由添加到 "layout" 路由下
  menuRouter.forEach((item) => {
    router.addRoute("layout", item);
  });
}
// 过滤树形结构中的节点
function filterTree(tree) {
  // 过滤树形结构中的节点
  // 只保留那些有 'path' 属性的节点
  return tree.filter(item => {
      // 检查当前节点是否有 'path' 属性
      const hasPath = item.path !== undefined;

      // 如果当前节点有子节点（children），递归调用 filterTree 函数
      // 对子节点进行同样的过滤操作
      if (item.children && item.children.length > 0) {
          item.children = filterTree(item.children);
      }

      // 最终，只保留那些有 'path' 属性的节点
      // 如果节点没有 'path' 属性，则它将被过滤掉
      return hasPath;
  });
}

// 转换
function filterAsyncRouter(routerMap) {
  const accessedRouters = [];
  routerMap.forEach((item) => {
    item.meta = item.meta ? item.meta : {};
    // 处理外部链接特殊路由
    if (item.meta.type == "iframe") {
      item.meta.url = item.path;
      item.path = `/i/${item.name}`;
    }
    // MAP转路由对象
    var route = {
      path: item.path,
      name: item.name,
      meta: item.meta,
      redirect: item.redirect,
      children: item.children ? filterAsyncRouter(item.children) : null,
      component: loadComponent(item.component),
    };
    accessedRouters.push(route);
  });
  return accessedRouters;
}

// 加载组件
function loadComponent(component) {
  if (component) {
    return modules[`../views/${component}/index.vue`];
  } else {
    return () => import("@/layout/other/empty.vue");
  }
}

// 路由扁平化
function flatAsyncRoutes(routes, breadcrumb = []) {
  let res = [];
  routes.forEach((route) => {
    const tmp = { ...route };
    if (tmp.children) {
      let childrenBreadcrumb = [...breadcrumb];
      childrenBreadcrumb.push(route);
      let tmpRoute = { ...route };
      tmpRoute.meta.breadcrumb = childrenBreadcrumb;
      delete tmpRoute.children;
      res.push(tmpRoute);
      let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb);
      childrenRoutes.map((item) => {
        res.push(item);
      });
    } else {
      let tmpBreadcrumb = [...breadcrumb];
      tmpBreadcrumb.push(tmp);
      tmp.meta.breadcrumb = tmpBreadcrumb;
      res.push(tmp);
    }
  });
  return res;
}

// 过滤树
function treeFilter(tree, func) {
  return tree
    .map((node) => ({ ...node }))
    .filter((node) => {
      node.children = node.children && treeFilter(node.children, func);
      return func(node) || (node.children && node.children.length);
    });
}
export default router;
